package com.blockchain.securewallet.utils;

import com.blockchain.securewallet.btc.BTCUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Chain-Cloud on 2018/6/28.
 */

public class EosSignUtil {

    private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");


    public static String transfer(String pk, String contractAccount, String from, String to, String quantity, String memo)
            throws Exception {
        // get chain info
//        ChainInfo info = getChainInfo();
        ChainInfo info = new ChainInfo();
        // get block info
//        Block block = getBlock(info.getLastIrreversibleBlockNum().toString());
        Block block = new Block();
        // tx
        Tx tx = new Tx();
        tx.setExpiration(info.getHeadBlockTime().getTime() / 1000 + 60);
        tx.setRef_block_num(info.getLastIrreversibleBlockNum());
        tx.setRef_block_prefix(block.getRefBlockPrefix());
        tx.setNet_usage_words(0l);
        tx.setMax_cpu_usage_ms(0l);
        tx.setDelay_sec(0l);
        // actions
        List<TxAction> actions = new ArrayList<>();
        // data
        Map<String, Object> dataMap = new LinkedHashMap<>();
        dataMap.put("from", from);
        dataMap.put("to", to);
        dataMap.put("quantity", new DataParam(quantity, DataType.asset, Action.transfer).getValue());
        dataMap.put("memo", memo);
        // action
        TxAction action = new TxAction(from, contractAccount, "transfer", dataMap);
        actions.add(action);
        tx.setActions(actions);
        // sgin
        String sign = Ecc.signTransaction(pk, new TxSign(info.getChainId(), tx));
        // data parse
        String data = Ecc.parseTransferData(from, to, quantity, memo);
//        return sign;
        // reset data
        action.setData(data);
        // reset expiration
        tx.setExpiration(dateFormatter.format(new Date(1000 * Long.parseLong(tx.getExpiration().toString()))));

        return BTCUtils.toHex(pushTransaction("none", tx, new String[] { sign }).getBytes());
    }

    private static String pushTransaction(String compression, Tx pushTransaction, String[] signatures) {
        ObjectMapper mapper = new ObjectMapper();
        String mapJakcson = null;
        try {
            mapJakcson = mapper.writeValueAsString(new TxRequest(compression,
                    pushTransaction, signatures));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return mapJakcson;
    }


}
